# encoding: utf-8

import os
from glob import glob
from tqdm import tqdm

new_base_path = "./new_files"
if not os.path.exists(new_base_path):
    os.mkdir(new_base_path)

path = "E:/data/m3u8_datas/*.m3u8"


def get_file_name(old_path: str) -> str:

    origin_file_name = os.path.basename(old_path)
    origin_file_name = origin_file_name.replace(".m3u8", ".mp4")
    new_name = "_".join(origin_file_name.split()).strip("_")

    return os.path.join(new_base_path, new_name)


files = glob(path)
for m3file in tqdm(files):
    new_file_name = get_file_name(m3file)
    if os.path.exists(new_file_name):
        continue
    with open(m3file, "r", encoding="utf-8") as f:
        lines = f.readlines()
    m3_data = bytes()

    for line in lines:
        if line.startswith("#"):
            continue

        line = line.strip()

        data_path = line.split("VideoData/")[-1]
        data_path2 = "E:/data/m3u8_datas/" + data_path
        if os.path.exists(data_path2):
            with open(data_path2, "rb") as ff:
                m3_data += ff.read()

    with open(new_file_name, "wb") as f:
        f.write(m3_data)
    # break
